package com.woniuxy.microgoldservice.timetask;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.woniuxy.microgoldservice.bean.GoldPriceInfo;
import com.woniuxy.microgoldservice.mapper.GoldAccumulateMapper;
import com.woniuxy.microgoldservice.mapper.GoldPriceMapper;
import com.woniuxy.microgoldservice.mapper.GoldPurchaseMapper;
import com.woniuxy.microgoldservice.service.IGoldAccumulateService;
import com.woniuxy.microgoldservice.service.IGoldpriceService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Collections;

/**
 * @author hongbin
 * @date 2021-04-08 11:29
 * Description：定时任务
 */
@Component
@Slf4j
public class TimeTask {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private IGoldAccumulateService goldAccumulateService;

    @Resource
    private GoldAccumulateMapper accumulateMapper;

    @Resource
    private IGoldpriceService goldpriceService;

    @Resource
    private GoldPriceMapper goldPriceMapper;

    @Resource
    private GoldPurchaseMapper goldPurchaseMapper;



    /**
    * @Author: hongbin
    * @Description: 每10分钟获取一次黄金价格数据
    * @DateTime: 19:42 2021/4/15
    * @Params: []
    * @Return void
    */
    @Transactional(rollbackFor = Exception.class)
    @Scheduled(cron = "0 0/10 * * * *")
    public void getWeather() {

        try {
            String appCode = accumulateMapper.selectAppCode();

            Calendar cal = Calendar.getInstance();
            int sec = cal.get(Calendar.SECOND);
            int min = cal.get(Calendar.MINUTE);
            int hour = cal.get(Calendar.HOUR_OF_DAY);
            String time=hour+":"+min+":"+sec;
            boolean b = "0:0:0".equals(time);

            //发送get请求获取黄金实时数据
            String appcode = appCode;

            String url = "https://jisugold.market.alicloudapi.com/gold/shgold";
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "APPCODE " + appcode);
            HttpEntity<String> entity = new HttpEntity<String>(headers);
            ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

            //封装对象存入数据库
            String body = result.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject.getIntValue("status") != 0) {
                System.out.println(jsonObject.getString("msg"));
                return;
            }
            String res = jsonObject.getString("result");
            JSONArray jsonArray = JSONArray.parseArray(res);
            String dataTypeName = goldAccumulateService.selectDataTypeName();
            JSONObject json = JSONObject.parseObject(dataTypeName);
            dataTypeName = json.getString("data");
            //循环取出相应字段
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject obj = (JSONObject) jsonArray.get(i);
                String typename = obj.getString("typename");

                if (dataTypeName == null) {
                    return;
                }
                if (typename.equals(dataTypeName)) {
                    String price = obj.getString("price");
    //                        String openingprice = obj.getString("openingprice");
    //                        String maxprice = obj.getString("maxprice");
    //                        String minprice = obj.getString("minprice");
                    String changepercent = obj.getString("changepercent");
    //                        String lastclosingprice = obj.getString("lastclosingprice");
    //                        String tradeamount = obj.getString("tradeamount");
    //                        String updatetime = obj.getString("updatetime");
    //                        System.out.println(type + " " + typename + " " + price + " " + openingprice + " " + maxprice + " "
    //                                + minprice + " " + changepercent + " " + lastclosingprice + " " + tradeamount + " "
    //                                + updatetime);

                    GoldPriceInfo goldPriceInfo = new GoldPriceInfo();
                    goldPriceInfo.setPrice(Double.parseDouble(price));
                    goldPriceInfo.setChangePercent(Double.parseDouble(changepercent));
                    goldPriceInfo.setReferencePrice(0.00);


                    //查询上架商品的id
                    Long productId = accumulateMapper.selectProId();
                    goldPriceInfo.setProductId(productId);
                    if(b){
                        int number = goldpriceService.insertZeroTime(goldPriceInfo);
//                        log.info("<====typeName====" + productId + "=======>");
//                        log.info("===========添加了" + number + "条金价信息===========");
                    }
                    int insert = goldpriceService.insert(goldPriceInfo);
//                    log.info("<====typeName====" + productId + "=======>");
//                    log.info("===========添加了" + insert + "条金价信息===========");


                    //计算总资产
                    Long proId = goldPriceMapper.selectProId();
                    BigDecimal todayGoldPrice = new BigDecimal(goldPriceMapper.getTodayGoldPrice(proId).getPrice());
                    goldPurchaseMapper.setMonetary(todayGoldPrice);
                    break;
                }

            }
        } catch (Exception e) {
            log.info("接口数据用完了，请尽快充值！！！！！！！");
        }
    }



    /**
    * 每天0:0:0计算黄金利息,累积收益，昨日收益，持有收益，持有收益率，近30天收益率
    */
    @Scheduled(cron="0 0 0 * * *")
    public void setReferencePrice() {
        log.info("现在时间是凌晨");
        goldpriceService.setEarnings();
    }



}
